const express = require('express')
const app = express()

const logger = require('morgan')
const expressSwagger = require('express-swagger-generator')(app)
const { swaggerOptions } = require('./config')
const db = require('./utils/db')
const api = require('./routes/api')
const ExceptionHandler = require('./middleware/ExceptionHandler')

db.on('connected', () => {
  console.log('mongodb is connected!');
})
db.on('disconnected', () => {
  console.log('mongodb is disconnected!');
})

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header('Access-Control-Max-Age', '600')
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next()
})

app.use('/static', express.static('public'))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(logger('dev'))
app.use('/api', api)
expressSwagger(swaggerOptions)

app.use(ExceptionHandler)

app.listen(5000, () => {
  console.log('app is run on 5000')
})